<?php
namespace app\user\controller;
use think\Db;
use EasyWeChat\Foundation\Application;
use EasyWeChat\Payment\Order;
/**
 * 获取
 *
 */
class User extends Common
{
    public function index()
    {
    	
    }
    //用户详情
    public function getinfo()
    {
        $oid = 1;
    	$openid = mwdecrypt(input('param.openid'));

        //获取服务电话
        $info['operator'] = Db::name('operator')->where('id',$oid)->field('name,logo,servicephone')->find();

    	//获取用户详情
    	$info['user'] = Db::name('user')
            ->where('oid',$oid)
    		->where('openid',$openid)
    		->find();
    	if($info){
            if($info['operator']['logo']){
                $info['operator']['logo'] = config('resourceurl').$info['operator']['logo'];
            }
            return $info;
        }else{
            return '';
        }

    }

    /**
     *更新用户
     *
     */
    public function updateuser()
    {
        $oid = 1;
        $postData = input('param.');
        $openId = mwdecrypt($postData['openid']);
        $user = $postData['user'];

        //如果有获取到用户信息
        if ($user) {
            $data['oid'] = $oid;
            $data['name'] = isset($user['name']) ? $user['name'] : '';
            $data['picture'] = isset($user['picture']) ? $user['picture'] : '';
            $data['gender'] = isset($user['gender']) ? $user['gender'] : '';
            $data['country'] = isset($user['country']) ? $user['country'] : '';
            $data['province'] = isset($user['province']) ? $user['province'] : '';
            $data['city'] = isset($user['city']) ? $user['city'] : '';

            //更新用户
            $res = Db::name('user')->where(['openid' => $openId])->update($data);

            if ($res) {
                $info = ['code' => 1, 'info' => '更新成功'];
            } else {
                $info = ['code' => 2, 'info' => '更新失败'];
            }
        } else {
            $info = ['code' => 2, 'info' => '更新失败'];
        }
        return $info;
    }

    //获取关于我们信息
    public function getabout(){
        $oid = 1;
        $info['operator'] = Db::name('operator')->where('id',$oid)->field('logo,introduce')->find();
        if($info){
            if($info['operator']['logo']){
                $info['operator']['logo'] = config('resourceurl').$info['operator']['logo'];
            }
            return $info;
        }else{
            return '';
        }

    }

    /**
     *添加用户数据
     *
     */
    public function adduser(){
        $data = input('param.');
        //$user = $data['user'];
        $user['oid'] = 1;
        $user['openid'] =mwdecrypt($data['openid']);
        $user['create_time'] = time();

        if($user['openid']){
            $isadd = Db::name('user')->where('oid',$user['oid'])->where('openid',$user['openid'])->field('id')->find();
            if(!$isadd){
                if(Db::name('user')->insert($user)){
                    $res['code'] = 1;
                    $res['info'] = '添加成功！';
                    return $res;
                }else{
                    $res['code'] = 2;
                    $res['info'] = '添加到数据库失败！';
                    return $res;
                }
            }else{
                $res['code'] = 0;
                $res['info'] = '用户已经存在了';
                return $res;
            }
        }else{
            $res['code'] = 3;
            $res['info'] = '信息不完整！';
            return $res;
        }
    }


    //修改用户信息
    public function edituser(){

    }
    //获取余额
    /**
     *小程序-获取余额
     *
     */
    public function getbalance(){
        $oid = 1;
        $openid = mwdecrypt(input('param.openid'));

        $info = Db::name('user')
            //->where('oid',$oid)
            ->where('openid',$openid)
            ->field('balance,deposit')
            ->find();
        return $info;
    }
    //获取余额信息
    public function getbalanceinfo(){

        $oid = 1;
        //$uid = input('param.uid');
        $openid = mwdecrypt(input('param.openid'));

        $res['balance'] = Db::name('user')
            ->where('oid',$oid)
            ->where('openid',$openid)
            ->field('id,balance')
            ->find();
        $recharge = Db::name('rechargeorder')
            ->where('oid',$oid)
            ->where('uid',$res['balance']['id'])
            ->where('pay_status',1)
            ->where('balance','>',0)
            ->select();
        if($recharge){
            foreach ($recharge as $key => $value) {
                $value['pay_mode']==1?$types = '微信':$types = '支付宝充值';
                $list[] = array(
                    'id' =>$value['id'],
                    'name' => $types.'充值',
                    'date' => date("Y-m-d H:i:s",$value['payment_date']),
                    'amount' =>$value['balance'],
                    'types' =>'recharge',
                );
            }


            $lease = Db::name('leaseorder')
                ->where('oid',$oid)
                ->where('uid',$res['balance']['id'])
                ->where('status',2)
                ->where('real_amount','>',0)
                ->select();
            foreach ($lease as $key => $value) {

                $list[] = array(
                    'id' =>$value['id'],
                    'name' => $value['name'],
                    'date' => date("Y-m-d H:i:s",$value['endtime']),
                    'amount' =>$value['real_amount'],
                    'types' =>'lease',
                );
            }

            $res['list'] = arraySort($list, 'date','DESC');
        }


        return $res;

    }

    //获取充值信息
    public function rechargeinfo(){

        $oid = 1;
        $openid = mwdecrypt(input('param.openid'));
        //获取用户余额信息
        $data['user'] = Db::name('user')->where('oid',$oid)->where('openid',$openid)->field('balance,deposit')->find();
        //获取运营商充值信息
        $data['operator'] = Db::name('operator')->where('id',$oid)->cache(true)->field('deposit,prepaidamount')->find();
        
        return $data;
    }
    //充值
    public function dorecharge(){
        $oid = 1;
        $openid = mwdecrypt(input('param.openid'));
        $time = time();
        $user = Db::name('user')->where('oid',$oid)->where('openid',$openid)->field('id')->find();

        $order = Db::name('rechargeorder')
            ->where('oid',$oid)
            ->where('uid',$user['id'])
            ->where('balance',input('param.balance'))
            ->where('deposit',input('param.deposit'))
            ->where('pay_status',0)
            ->where('create_time','>',$time-30)
            ->where('is_delete',1)
            ->field('create_time')
            ->find();
        if($order){
            $delay = 30 - ($time - $order['create_time']);
            $result['code']= 0 ;
            $result['info']= '请不要重复充值,'.$delay.'秒后再试。' ;
            return $result;
        }
        $data = array(
            'oid' => $oid,
            'order_no' => '201' . date('ymdHis') . rand(1000, 9999),
            'uid' => $user['id'],
            'balance' => input('param.balance'),
            'deposit' => input('param.deposit'),
            'payable_amount' => input('param.amount'),
            'create_time' => $time,
        );
        if($data['payable_amount']==($data['balance']+$data['deposit'])&&$data['payable_amount']>0){
            Db::name('rechargeorder')->insert($data);
            $orderinfo = array(
                'oid' => $oid,
                'openid' => $openid,
                'orderno' => $data['order_no'],
                'detail' => '微信充值',
                'price' => $data['payable_amount'],
                //'price' => 0.01,
                'notify_url' =>config('website').'/user/Wechat/rechargenotify/oid/'.$oid,
            );
            $Wechat = controller('Wechat');
            $result = $Wechat->smallapppay($orderinfo);
            return $result;
        }else{
            $result['code']= 0 ;
            $result['info']= '非法请求' ;
            return $result;
        }
    }
    /**
     *小程序-充值押金
     *
     */
    public function rechargedeposit(){
        $oid = 1;
        $openid = mwdecrypt(input('param.openid'));

        //获取客户数据
        $user = Db::name('user')
            ->where('oid',$oid)
            ->where('openid',$openid)
            ->field('id')
            ->find();

        //获取运营数据
        $seller = Db::name('operator')->where('id',$oid)->field('deposit')->find();

        $data = array(
            'oid' => $oid,
            'order_no' => '202' . date('ymdHis') . rand(1000, 9999),
            'uid' => $user['id'],
            'deposit' => $seller['deposit'],
            'payable_amount' => $seller['deposit'],
            'create_time' =>time(),
        );
        Db::name('rechargeorder')->insert($data);
        $orderinfo = array(
            'oid' => $oid, 
            'openid' => $openid, 
            'orderno' => $data['order_no'],
            'detail' => '押金充值', 
            'price' => $data['payable_amount'], 
            'notify_url' =>config('website').'/user/Wechat/rechargenotify/oid/'.$oid,
        );
        $Wechat = controller('Wechat');
        $result = $Wechat->smallapppay($orderinfo);

        return $result;

    }
    //退押金
    public function returndeposit(){
        $oid = 1;
        $openid = mwdecrypt(input('param.openid'));
        //查询用户基本信息
        $user = Db::name('user')->where('oid',$oid)->where('openid',$openid)->field('id,balance,deposit')->find();
        //查询有没有未结束订单
        $isorder = Db::name('leaseorder')->where('oid',$oid)->where('uid',$user['id'])-> where('status','neq',2)-> count();
        $res = [];
        if(!$isorder){
            //获取后一个完成租借的订单
            $lastorder = Db::name('leaseorder')->where('oid',$oid)->where('uid',$user['id'])-> where('status',2) -> field('endtime')->order('endtime desc')-> find();
            //获取退押金延迟时间
            $operator = Db::name('operator')->where('id',$oid)->field('deposit_delay')->find();

            $deposit_delay = $operator['deposit_delay']*60;
            $endtime = $lastorder['endtime'];
            $time = time();
            //判断最后一个订单的归还时间和是否小于眼睛延迟
            if($time-$endtime < $deposit_delay){
                $res['info'] = '退款失败，最后一个订单结束'.$operator['deposit_delay'].'分钟后才能退款';
                $res['code'] = 5;
                return $res;
            }else{
                $order = Db::name('rechargeorder')
                    ->where('oid',$oid)
                    ->where('uid',$user['id'])
                    ->where('deposit','>',0)
                    ->where('pay_status',1)
                    ->where('refunddeposit','<=',0.00)
                    ->find();
                $refundNo = '401' . date('ymdHis') . rand(1000, 9999);
                if($user['balance']<0){//判断余额是否余额等于零
                    if($order['deposit']+$user['balance']==0){
                        $updateuser = Db::name('user')->where('id',$user['id'])->update(['deposit' => 0,'balance' => 0]);
                        if($updateuser){
                            $res['info'] = '退款成功！';
                            $res['code'] = 1;
                        }else{
                            $res['info'] = '用户信息更新失败！';
                            $res['code'] = 2;
                        }
                        return $res;
                    }elseif ($order['deposit']<$user['balance']) {
                        $res['info'] = '欠费金额大于押金金额，请先补足欠费金额';
                        $res['code'] = 2;
                        return $res;
                    }else{
                        $deposit = $order['deposit']+$user['balance'];
                        $balance = 0;
                    }

                }else{
                    $deposit = $order['deposit'];
                    $balance = $user['balance'];
                }

                $Wechat = controller('Wechat');
                $result = $Wechat->refund($order['order_no'],$refundNo,$order['real_amount']*100,$deposit*100,$order['oid']);

                //判断退款是否成功
                if($result['result_code']=='SUCCESS'&&$result['return_code']=='SUCCESS'){
                    $return = array(
                        'oid' => $oid,
                        'uid' => $user['id'],
                        'types' => 1,
                        'order_no' => $order['order_no'],
                        'refund_no' => $refundNo,
                        'transaction_id' => $result['transaction_id'],
                        'refund_time' => time(),
                    );
                    Db::name('refund')->insert($return);
                    $recharge = Db::name('rechargeorder')->where('order_no',$order['order_no'])->update(['refunddeposit' => $deposit]);
                    if(!$recharge){
                        $res['info'] = '订单信息更新失败！';
                    }
                    $updatebalance = Db::name('user')->where('id',$user['id'])->update(['balance' => $balance,'update_time' => time()]);
                    if ($user['balance']<0) {
                        $deposit = $deposit - $user['balance'];
                    }
                    $updatedeposit = Db::name('user')->where('id',$user['id'])->setDec('deposit', $deposit);
                    if(!$updatebalance || !$updatedeposit){
                        isset($res['info'])? $res['info'].= '用户信息更新失败！': $res['info']= '用户信息更新失败！';
                    }

                    if(empty($res)){
                        $res['info'] = '退款成功！';
                        $res['balance'] = $balance;
                        $res['code'] = 1;
                        return $res;
                    }else{
                        $res['info'] = isset($res['info'])? $res['info'] : '';
                        $res['code'] = 2;
                        return $res;
                    }
                }else{
                    $res['info'] = '退款失败！'. $result['err_code_des'];
                    $res['code'] = 3;
                    return $res;
                }
            }

        }else{
            $res['info'] = '失败！有订单未处理！';
            $res['code'] = 4;
            return $res;
        }


    }

}
